package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * 移动端用户模块控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;

    @Autowired
    private RedisTemplate redisTemplate;

//    @Autowired(required = false)
//    private CacheManager cacheManager;
    /**
     * 发送短信验证码
     * @return
     */

    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        if (!StringUtils.isEmpty(phone)){
            //1.生成4位数验证码
            String validateCode = ValidateCodeUtils.generateValidateCode4String(4);
            log.info("本次生成验证码为{}",validateCode);
            //2.发送短信验证码
//            SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,validateCode);
            //3.将验证码存入session域中
//            session.setAttribute(phone,validateCode);
            //3.1 验证码优化：使用redis缓存验证码。设置有效时间为1分钟
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(phone,validateCode,1, TimeUnit.MINUTES);
            return R.success("短信验证码发送成功！");
        }
        return R.error("短信验证码发送失败!");
    }

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, Object> map){
        //获取登录用户
        String phone = (String) map.get("phone");
        //获取用户输入的验证码
        String code = (String) map.get("code");
        //获取session域里的验证码
//        String validateCode = (String) session.getAttribute(phone);

        //优化：从redis中取出验证码。验证码有效期为1分钟
        String validateCode = (String) redisTemplate.opsForValue().get(phone);

        R<User> loginResult = userService.login(phone, code, validateCode);
        session.setAttribute("loginUser",loginResult.getData());
        return loginResult;

    }
    @RequestMapping("/loginout")
    public R<String> loginout(){
        session.invalidate();
        return  R.success("退出成功！");
    }
}
